package com.dragon.modules.yuegou.client.wechat_mini.service.impl;

import com.dragon.modules.yuegou.client.wechat_mini.client.AuthClient;
import com.dragon.modules.yuegou.client.wechat_mini.common.MiniConfig;
import com.dragon.modules.yuegou.client.wechat_mini.response.Code2SessionResponse;
import com.dragon.modules.yuegou.client.wechat_mini.response.UnionIdResponse;
import com.dragon.modules.yuegou.client.wechat_mini.security.AccessTokenService;
import com.dragon.modules.yuegou.client.wechat_mini.service.AuthService;
import com.dragon.modules.yuegou.web.Check;

/**
 * 认证服务实现
 * 
 * @author liuwu
 *
 */
public class AuthServiceImpl implements AuthService {

	/**
	 * 定义消息客户端
	 */
	private final AuthClient client;

	/**
	 * 小程序账号配置
	 */
	private final MiniConfig config;

	/**
	 * 凭证服务
	 */
	private final AccessTokenService tokenService;

	/**
	 * 构造一个订阅消息服务
	 * 
	 * @param client       认证接口客户端
	 * @param config       小程序账号配置
	 * @param tokenService 凭证服务
	 */
	public AuthServiceImpl(AuthClient client, MiniConfig config, AccessTokenService tokenService) {
		super();
		Check.notNull(client, "client is required");
		Check.notNull(tokenService, "tokenService is required");
		this.client = client;
		this.config = config;
		this.tokenService = tokenService;
	}

	@Override
	public Code2SessionResponse code2Session(String jsCode) {
		return client.code2Session(config.getAppid(), config.getSecret(), jsCode);
	}

	@Override
	public String getPaidUnionId(String openid, String transactionId) {
		return tokenService.executeAutoRetry(accessToken -> client.getPaidUnionId(accessToken, openid, transactionId),
				UnionIdResponse::getUnionid);
	}

	@Override
	public String getPaidUnionId(String openid, String outTradeNo, String mchId) {
		return tokenService.executeAutoRetry(
				accessToken -> client.getPaidUnionId(accessToken, openid, outTradeNo, mchId),
				UnionIdResponse::getUnionid);
	}

}
